package com.campus.controller;

import com.campus.domain.po.Activity;
import com.campus.service.ActivityService;
import com.campus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @PreAuthorize("isAuthenticated()")
    @PostMapping("/add")
    public R addActivity(@RequestBody Activity activity) {
        Activity savedActivity = activityService.saveActivity(activity);
        return R.success(savedActivity);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/delete/{id}")
    public R deleteActivity(@PathVariable Integer id) {
        boolean removed = activityService.deleteActivityById(id);
        return removed ? R.success(200) : R.error(500, "Failed to delete activity");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/update")
    public R updateActivity(@RequestBody Activity activity) {
        Activity updatedActivity = activityService.updateActivity(activity);
        return updatedActivity != null ? R.success(updatedActivity) : R.error(500, "Failed to update activity");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public R getActivity(@PathVariable Integer id) {
        Activity activity = activityService.getActivityById(id);
        return activity != null ? R.success(activity) : R.error(500, "Activity not found");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/list")
    public R getActivityList(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        return R.success(activityService.getActivityList(name, status, page, size));
    }
}
